package org.fuxia.im.listeners;

import java.util.List;
import java.util.Map;

import javax.swing.SwingUtilities;

import org.fuxia.im.common.ClientConst;
import org.fuxia.im.common.ClientContext;
import org.fuxia.im.common.CommonDialog;
import org.fuxia.im.core.entries.ECResponse;
import org.fuxia.im.core.listeners.Listener;
import org.fuxia.im.core.utils.ObjectUtil;
import org.fuxia.im.entities.User;
import org.fuxia.im.gui.Login;
import org.fuxia.im.gui.Logining;
import org.fuxia.im.gui.Main;
import org.fuxia.im.gui.util.FileUtil;

import com.alibaba.fastjson.JSONArray;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class LoginResponseListener implements Listener {

	public void trigger(Object param) {
		ECResponse resp = (ECResponse) param;
		Integer statusCode = resp.getStatusCode();
		switch (statusCode) {
		case 200:
			handlerSuccess(resp);
			break;
		case 400:
			handlerError(resp);
			break;
		default:
			break;
		}
	}

	private void handlerError(ECResponse resp) {
		Logining loging = (Logining) ClientContext
				.removeKey(ClientConst.LOGING_WINDOW);
		loging.setVisible(false);
		loging.dispose();
		Login login = (Login) ClientContext.getValue(ClientConst.LOGIN_WINDOW);
		login.setVisible(true);
		CommonDialog.showErrorMessageDialog(login.getPannel(),
				resp.get("loginResult").toString());
	}

	private void handlerSuccess(final ECResponse resp) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				Object o = ClientContext.removeKey(ClientConst.LOGING_WINDOW);
				if (o != null) {
					Logining loging = (Logining) o;
					loging.setVisible(false);
					loging.dispose();
				}
				User user = ObjectUtil.getObjectByJsonStr(resp.get("user")
						.toString(), User.class);
				final Map friends = ObjectUtil.getObjectByJsonStr(
						resp.get("friends").toString(), Map.class);
				List<JSONArray> groups = ObjectUtil.getObjectByJsonStr(resp
						.get("chatGroups").toString(), List.class);
				ClientContext.putValue(ClientConst.FRIENDS, friends);
				ClientContext.putValue(ClientConst.CURRENT_USER, user);
				ClientContext.putValue(ClientConst.GROUPS, groups);
				Main mainWindow = new Main(friends);
				ClientContext.putValue(ClientConst.MAIN_WINDOW, mainWindow);
				mainWindow.showWindow();
				Object rem = ClientContext.removeKey("REMEMBER_USER") ;
				if(rem!=null && (Boolean)rem) {
					String sysConfigPath = ClientContext.getValue("sys-data-file",String.class) ;
					FileUtil.writeInfo(user.getUserCode(), ClientContext.removeKey("PASS").toString(), sysConfigPath);
				}else {
					String sysConfigPath = ClientContext.getValue("sys-data-file",String.class) ;
					FileUtil.removeKey(user.getUserCode(), sysConfigPath);
				}
			}
		});
	}
}
